# -*- coding: utf-8 -*-

import os
import sys
import logging
from logging import handlers

import config


logs_path = "./logs"
if not os.path.exists(logs_path):
    os.makedirs(logs_path)
    pass

log_file_name = 'log.log'
log_format = '%(asctime)s - %(thread)d - [%(levelname)s] - {%(pathname)s:%(lineno)d} (%(funcName)s) - %(message)s'

log_file_max_bytes = 10 * 1024 * 1024
log_file_backup_count = 100


def init_logger(logger=logging.getLogger(__name__)):
    # 控制台日志
    console_handler = logging.StreamHandler(stream=sys.stdout)

    # 文件日志名称
    log_file_name = 'logger.log'

    # 按大小分割日志文件
    file_handler = handlers.RotatingFileHandler(filename=os.path.join(logs_path, log_file_name),
                                                maxBytes=log_file_max_bytes,
                                                backupCount=log_file_backup_count)

    # 按时间分割日志文件
    # file_handler = handlers.TimedRotatingFileHandler(filename=config.log_file_name,
    #                                                  when='D', interval=10,
    #                                                  backupCount=config.log_file_backup_count)
    """
    when=''
    S
    M
    H
    D
    W
    midnight
    """
    # 日志格式
    formatter = logging.Formatter(log_format)
    console_handler.setFormatter(fmt=formatter)
    file_handler.setFormatter(fmt=formatter)

    # 日志级别
    console_handler.setLevel(logging.DEBUG)
    file_handler.setLevel(logging.DEBUG)
    logger.setLevel(logging.DEBUG)

    # 日志对象添加处理器
    logger.addHandler(console_handler)
    logger.addHandler(file_handler)

    logger.debug('init logger')
    pass


if __name__ == "__main__":
    logger = logging.getLogger(config.webpy_app_log)
    init_logger(logger)
    pass
